package com.yunfinal.api.service.doc;

import com.jfinal.log.Log;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentLinkedQueue;


/**
 * API 报告单
 *  com.yunfinal.api.service.doc.ApiReportSocket
 */
@ServerEndpoint("/api/report.ws")
public class ApiReportSocket {
    static String Url = "/api/report.ws";
    protected static Log log = Log.getLog(ApiReportSocket.class);
    protected static ConcurrentLinkedQueue<ApiReportSocket> aueue = new ConcurrentLinkedQueue<>();

    /**
     * 获取 ApiReportSocket 的请求地址
     * @param request
     * @return 请求地址
     */
    public static String getWsUrl(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(),
                url.length()).substring(url.indexOf(":"));
        return "ws".concat(tempContextUrl).concat(Url);
    }

    public static int sendMsg(String msg){
        for (ApiReportSocket socket : aueue) {
            socket.sendMyMsg(msg);
        }
        return aueue.size();
    }

    // Socket

    protected Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        aueue.add(this);
        log.info("有人进入请求报告大厅了，在线数：" + aueue.size());
    }

    @OnClose
    public void onClose(){
        aueue.remove(this);
        log.info("有人离开报告大厅了，在线数：" + aueue.size());
    }

    protected void sendMyMsg(String msg){
        try {
            this.session.getBasicRemote().sendText(msg);
        } catch (Exception e) {
            log.error("ApiReportSocket-sendMyMsg-error:", e);
        }
    }

}
